// 配置axios
import Vue from "vue";
import axios from "axios";
import i18n from '@/i18n'
import router from '@/router'
import { Message } from "element-ui";
import { clearLoginInfo } from "@/utils";
import Cookies from "js-cookie";

let http = axios.create({
  // baseURL: baseURL,
  // baseURL: '/api',
  timeout: 1000 * 180,
  withCredentials: true
});
/**
 * 请求拦截
 */
http.interceptors.request.use(
  config => {
    config.headers["Accept-Language"] = Cookies.get("languages") || "zh-CN";
    config.headers["token"] = Cookies.get("token") || "";
    // 默认参数
    // var defaults = {};
    // 防止缓存，GET请求默认带_t参数
    if (config.method === "get") {
      config.params = {
        ...config.params,
        ...{ _t: new Date().getTime() }
      };
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = Vue.$qs.stringify(config.data)
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
/**
 * 响应拦截
 */
var messageInstance = null;
http.interceptors.response.use(
  response => {
    if (response.data.code === 401 || response.data.code === 10001) {
      if (messageInstance) {
        messageInstance.close();
      }
      clearLoginInfo();
      messageInstance = Message.error(i18n.t('request.tokenTimeOut'));
      // window.location.reload();
      router.replace({path:"/login"})
      return Promise.reject(response.data.msg);
    }
    if (!response.data.code) {
      return response;
    } else if (response.data.code == 0) {
      return response;
    } else if (response.data.code != 500) {
      return response;
    }
  },
  err => {
    return Promise.reject(err);
  }
);
export default http;
